<?php

/**
 * Subclass for representing a row from the 'storage' table.
 *
 * 
 *
 * @package lib.model
 */ 
class Storage extends BaseStorage
{
	
    const PERM_READ             = 1;
    const PERM_WRITE            = 2;
	
	/**
	 * Returns path to storage directory, i.e. /home/www/sf10/data
	 * 
	 * @return string
	 */
	public static function getPathToStorage()
	{
	   return sfConfig::get('sf_data_dir', '/path/to/data/dir') . DIRECTORY_SEPARATOR . 'storage/';
	}
	
	
	/**
	 * Returns array of allowed MIME types, taken from app.yml
	 * 
	 * @return array
	 */
	public static function getAllowedMimeTypes()
	{
		return sfConfig::get(
		    'app_storage_allowed_mimes'
		    , array(
	            'image/jpeg'
	            , 'image/png'
	            , 'image/gif'
	            , 'image/x-png'
	            , 'image/pjpeg'		      
		    )
		);
	}
	
	
	/**
	 * Returns size of file in human readable format, i.e. 1.5Mb
	 */
	public function getFileSizeFmt()
	{
		if( $this->file_size < 1024 )
		{
			return sprintf('%db', $this->file_size);
		}
		
		$s = array('bytes', 'kb', 'MB', 'GB', 'TB', 'PB');
        $e = floor(log($this->file_size) / log(1024));
 
        return sprintf('%.2f '.$s[$e], ($this->file_size / pow(1024, floor($e))));
	}
	
	/**
	 * Returns true if this file is allowed to be outputed to browser (by its MIME type)
	 * 
	 * @return boolean
	 */
	public function allowToOutput()
	{
//        debugvar('Is MIME ' . $this->mime_type . ' is in allowed to output?');
		return in_array($this->mime_type, Storage::getAllowedMimeTypes());
	} 
	
	public function hydrate(ResultSet $rs, $startcol = 1)
	{
		$this->setCulture(sfContext::getInstance()->getUser()->getCulture());
        return parent::hydrate($rs, $startcol);
	}
	
	
	/**
	 * Overrided method, also sets file extension
	 * 
	 * @param string $v
	 */
	public function setRealName($v)
	{
		if( $v )
		{
            $pos = strrpos($v, '.');
            if( $pos >= 0 )
            {
                $this->setExt(strtolower(substr($v, $pos + 1)));
            }
		}
	    parent::setRealName($v);
	}
	
	/**
	 * Returns name of status by its ID from MyConstants
	 */
	public function getStatusName()
	{
	   return MyConstants::getStatusName($this->status_id);
	}
	
    /**
     * Overrided method. Deletes from DB and files from Storage directory
     */
	public function delete( $con = null )
	{
        if( $this->uname )
        {
            $fileToDelete = sprintf('%s%s', Storage::getPathToStorage(), $this->getUname());
            if( file_exists($fileToDelete) )
            {
                @unlink($fileToDelete);
            }
	    }
	   
	    parent::delete($con);
	}
}
